/*
* 完成生产工序
* */

import 'dart:convert';

import 'package:center_beijing/api/component_api.dart';
import 'package:center_beijing/api/product_api.dart';
import 'package:center_beijing/common/logutil.dart';
import 'package:center_beijing/common/notification.dart';
import 'package:center_beijing/common/numLengthInputFormatter.dart';
import 'package:center_beijing/common/styles.dart';
import 'package:center_beijing/config/global_config.dart';
import 'package:center_beijing/config/routeConfig.dart';
import 'package:center_beijing/models/selectItem.dart';
import 'package:center_beijing/widgets/add_custom_input_widget.dart';
import 'package:center_beijing/widgets/checkbox_widget.dart';
import 'package:center_beijing/widgets/custom_input_widget.dart';
import 'package:center_beijing/widgets/custom_loading_widget.dart';
import 'package:center_beijing/widgets/custom_radio.dart';
import 'package:center_beijing/widgets/custom_select_widget.dart';
import 'package:center_beijing/widgets/imageSelect_widget.dart';
import 'package:center_beijing/widgets/textarea_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart' as Go;
import 'package:dio/dio.dart' as ImageForm;
import 'package:images_picker/images_picker.dart';
import 'dart:io';

import 'package:images_picker/images_picker.dart';
import 'package:http_parser/http_parser.dart';
class CompleteProcess extends StatefulWidget {
  @override
  _CompleteProcessState createState() => _CompleteProcessState();
}

class _CompleteProcessState extends State<CompleteProcess>
    with SingleTickerProviderStateMixin {
  AnimationController _controller;
  List<SelectItems> moTaiList = [];
  SelectItems selectMoTai = SelectItems();
  var type = Go.Get.arguments['type'];
  CustomLoading loading = CustomLoading.withMessage('提交中...');
  CustomLoading loading2 = CustomLoading.withMessage('请稍候...');
  final TextEditingController measure = TextEditingController(); //实际测量
  var workStageDetail = Go.Get.arguments['procedure'];
  var compDetail = Go.Get.arguments['compDetail'];
  var formList = [];
  var remark = '';
  List<Media> photos = [];
  ImageForm.FormData formData;
  List passPhoto = [];
  List checkValue = [];
  bool qualified = true;

  @override
  void initState() {
    _controller = AnimationController(vsync: this);
    super.initState();
    this.getCheckDetail();
    this.getMoTai();
  }

  /*
  * 获取表单
  * */
  getCheckDetail() async {
    loading2.show(delay: 30);
    var result = await getCheckItem(workStageDetail['id']);
    loading2.dismiss();
    if (result != null) {
      this.setState(() {
        formList = result;
      });
    }
    LogUtil.d(result);
  }

  /*
  * 获取模台
  * */
  getMoTai() async {
    var result = await getMoTaiList(GlobalConfig.selectFactory.value);
    if (result != null) {
      List<SelectItems> tem = [];
      result.forEach((item) {
        tem.add(SelectItems(label: item['pedestalId'], value: item['id']));
      });
      this.setState(() {
        moTaiList = tem;
      });
    }
    LogUtil.d(result);
  }

  getFormItem(value, index) {
    if (value['isS'] != null) {
      return Container(
        margin: EdgeInsets.only(top: Styles.spacing8),
        alignment: Alignment.centerLeft,
        color: Colors.white,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              padding: EdgeInsets.fromLTRB(
                  Styles.spacing8, Styles.spacing8, Styles.spacing8, 0),
              child: RichText(
                  text: TextSpan(children: [
                    value['viewInput']['validate']['required']?TextSpan(
                      text: '*',
                      style: TextStyle(
                          fontSize: Styles.NormalFont, color: Styles.RedColor),
                    ):Container(),
                    TextSpan(
                      text: '检查项目: ${value['viewInput']['title']}',
                      style: TextStyle(
                          fontSize: Styles.NormalFont,
                          color: Styles.DetailColor),
                    ),
                  ])),
            ),

            Container(
              padding: EdgeInsets.fromLTRB(
                  Styles.spacing8, Styles.spacing8, Styles.spacing8, 0),
              child: Text(
                '标准尺寸: ${value['viewNum']['checkNorm']}',
                style: TextStyle(
                    color: Styles.DetailColor, fontSize: Styles.NormalFont),
              ),
            ),
            Container(
              padding: EdgeInsets.fromLTRB(
                  Styles.spacing8, Styles.spacing8, Styles.spacing8, 0),
              child: Text(
                '偏差下/上限: ${value['viewNum']['checkMin']}  ${value['viewNum']['checkMax']}',
                style: TextStyle(
                    color: Styles.DetailColor, fontSize: Styles.NormalFont),
              ),
            ),
            Container(
              color: Colors.white,
              margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
              padding:
                  EdgeInsets.fromLTRB(Styles.spacing8, 0, Styles.spacing8, 0),
              child: AddCustomInputWidget(
                keyboardType: TextInputType.numberWithOptions(decimal: true),
                inputformat: [
                  LengthLimitingTextInputFormatter(20),
                  NumLengthInputFormatter(digit: 2)
                ],
                titleFont: Styles.NormalFont,
                title: '实际测量',
                placeHold: '请输入',
                clearAll: false,
                require: false,
                isAdd: false,
                inputNumber: formList[index]['viewNum']['checkNum'] != null
                    ? int.parse(formList[index]['viewNum']['checkNum'])
                    : 1,
                textChange: (textController) {
                  formList[index]['viewInput']['value'] =
                      textController.map((item) {
                    return item.text;
                  }).toList();
                  formList[index]['viewInput']['valueStr'] =
                      formList[index]['viewInput']['value'];
                },
              ),
            ),
          ],
        ),
      );
    } else {
      if (value['type'] == 'radio') {
        formList[index]['value'] = value['options'][0]['value'];
        formList[index]['valueStr'] = value['options'][0]['label'];
        return Container(
          margin: EdgeInsets.only(top: Styles.spacing8),
          color: Colors.white,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                padding: EdgeInsets.fromLTRB(
                    Styles.spacing8, Styles.spacing8, Styles.spacing8, 0),
                child: Text(
                  '检查项目: ${value['title']}',
                  style: TextStyle(
                      color: Styles.DetailColor, fontSize: Styles.NormalFont),
                ),
              ),
              CustomRadio(
                  selectList: value['options'].map<SelectItems>((item) {
                    return SelectItems(
                        label: item['label'], value: item['value']);
                  }).toList(),
                  title: '检查结果',
                  ifRequired: value['validate']['required'],
                  selectCallback: (item) {
                    LogUtil.d(value);
                    formList[index]['value'] = item.value;
                    formList[index]['valueStr'] = item.label;
                  })
            ],
          ),
        );
      } else if (value['type'] == 'checkbox') {
        return Container(
          margin: EdgeInsets.only(top: Styles.spacing8),
          color: Colors.white,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                color: Colors.white,
                padding: EdgeInsets.fromLTRB(
                    Styles.spacing8, Styles.spacing8, Styles.spacing8, 0),
                child: Text(
                  '检查项目: ${value['title']}',
                  style: TextStyle(
                      color: Styles.DetailColor, fontSize: Styles.NormalFont),
                ),
              ),
              Container(
                  margin: EdgeInsets.only(top: Styles.spacing8),
                  child: CheckBoxWidget(
                    labelText: '检查结果',
                    disabled: false,
                    ifRequired: value['validate']['required'],
                    items: value['options'].map<SelectItems>((item) {
                      return SelectItems(
                          label: item['label'], value: item['value']);
                    }).toList(),
                    defaultValue: '',
                    selectCallback: (value) {
                      LogUtil.d(value);
                      formList[index]['value'] = value.map((item) {
                        return item.value;
                      }).toList();
                      formList[index]['valueStr'] = value
                          .map((item) {
                            return item.label;
                          })
                          .toList()
                          .join(',');
                    },
                  ))
            ],
          ),
        );
      } else if (value['type'] == 'select') {
        return Container(
          color: Colors.white,
          margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
          child: CustomSelectWidget(
            require: value['validate']['required'],
            rightText: formList[index]['valueStr'] != null
                ? formList[index]['valueStr']
                : '请选择',
            items: value['options'].map<SelectItems>((item) {
              return SelectItems(label: item['label'], value: item['value']);
            }).toList(),
            selectCallback: (item) => this.setState(() {
              LogUtil.d(value);
              formList[index]['value'] = item.value;
              formList[index]['valueStr'] = item.label;
            }),
            title: value['title'] != null ? value['title'] : '--',
          ),
        );
      } else {
        return Container();
      }
    }
  }

  submit() async {
    var passList = [];
    this.formList.forEach((element) {
      if (element['viewInput'] != null) {
        for (var index = 0;
            index < element['viewInput']['value'].length;
            index++) {
          Map bbq = json.decode(json.encode(element));
          bbq['viewInput']['field'] =
              bbq['viewInput']['field'] + index.toString();
          bbq['viewInput']['value'] = element['viewInput']['value'][index];
          bbq['viewInput']['valueStr'] = element['viewInput']['value'][index];
          passList.add(bbq);
        }
      } else {
        passList.add(element);
      }
    });
    var pass = {
      'componentId': compDetail['id'],
      'workstageId': workStageDetail['id'],
      "operateContent": workStageDetail['workStageName'],
      "remark": this.remark,
      "operator": GlobalConfig.userInfo['name'],
      "operatorId": GlobalConfig.userInfo['userId'],
      "pedestalId": selectMoTai.value,
      'qualified':qualified,
      "formJson": json.encode(passList.map((item) {
        return item['viewInput'] != null ? item['viewInput'] : item;
      }).toList()),
      'attachments': this.passPhoto
    };
    var result = await subWorkStageForm(pass);
    loading.dismiss();
    if (result != null&&result=='') {
      bus.emit('refreshDetail');
      Fluttertoast.showToast(msg: '提交成功');
      Go.Get.back(result: 1);
    }
    LogUtil.d(result);
  }

  Future addImage() async {
    this.passPhoto = [];
    loading.show(delay: 30);
    if (this.photos.length > 0) {
      var temPhotos = [];
      temPhotos.addAll(this.photos);
      formData = new ImageForm.FormData.fromMap({
        "tenantId": GlobalConfig.tenantId,
      });
      for (int i = 0; i < temPhotos.length; i++) {
        Media asset = temPhotos[i];
        File file = File(asset.path);
        formData.files.add(MapEntry("files",
            await ImageForm.MultipartFile.fromFile(file.path.toString(),contentType: MediaType('image',file.path.toString().split('.').last))));
      }
      var result = await uploadImage(formData, GlobalConfig.tenantId);
      if (result != null && result.length > 0) {
        this.passPhoto = result;
        this.submit();
      }
    } else {
      this.submit();
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  /*
  * 验证必填项
  * */
  justifyInput() {
    if(type==0){
      if(selectMoTai.value==null){
        Fluttertoast.showToast(msg: '请选择模台');
        return false;
      }
    }
    for (var item in this.formList) {
      if (item['isS'] != null) {
        if (item['viewInput']['validate']['required']) {
          if (item['viewNum']['checkNum'] != null) {
            if (item['viewInput']['value']==null||item['viewInput']['value'].length <
                int.parse(item['viewNum']['checkNum'])) {
              Fluttertoast.showToast(msg: '请将${item['viewInput']['title']}输入完整');
              return false;
            }else{
              bool isEmpty = false;
              for(var element in item['viewInput']['value']){
                if(element==''){
                  isEmpty = true;
                  break;
                }
              }
              if(isEmpty){
                Fluttertoast.showToast(msg: '请将${item['viewInput']['title']}输入完整');
                return false;
              }
            }
          } else {
            if (item['viewInput']['value']==null||item['viewInput']['value'].length == 0) {
              Fluttertoast.showToast(msg: '请将${item['viewInput']['title']}输入完整');
              return false;
            }
          }
        }
      } else {
        if(item['validate']['required']){
          if(item['value']==null||item['value'].length==0){
            Fluttertoast.showToast(msg: '未选择${item['title']}');
            return false;
          }
        }
      }
    }
    return true;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('生产工序-' + workStageDetail['workStageName']),
        ),
        body: GestureDetector(
          onTap: () {
            FocusScope.of(context).requestFocus(FocusNode());
          },
          child: Container(
            color: Styles.MainBackgroundColor,
            padding: EdgeInsets.fromLTRB(
                0, 0, 0, MediaQuery.of(context).padding.bottom + 70),
            child: SingleChildScrollView(
              child: Column(
                children: [
                  type == 0
                      ? Container(
                          color: Colors.white,
                          margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                          child: CustomSelectWidget(
                            require: true,
                            rightText: selectMoTai.label != null
                                ? selectMoTai.label
                                : '请选择',
                            items: moTaiList,
                            selectCallback: (value) => this.setState(() {
                              selectMoTai = value;
                            }),
                            title: '选择模台',
                          ),
                        )
                      : Container(),
                  Container(
                    child: Column(
                      children: this.formList.asMap().keys.map<Widget>((index) {
                        return getFormItem(this.formList[index], index);
                      }).toList(),
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: Styles.spacing8),
                    color: Colors.white,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          padding: EdgeInsets.fromLTRB(
                              Styles.spacing8, Styles.spacing8, Styles.spacing8, 0),
                          child: Text(
                            '是否合格',
                            style: TextStyle(
                                color: Styles.DetailColor, fontSize: Styles.NormalFont),
                          ),
                        ),
                        CustomRadio(
                            selectList: [SelectItems(
                                label: '合格', value: '1'),SelectItems(
                                label: '不合格', value: '2')],
                            title: '检查结果',
                            ifRequired: true,
                            selectCallback: (item) {
                              LogUtil.d(item);
                              this.setState(() {
                                qualified = (item.value=='1');
                              });
                            })
                      ],
                    ),
                  ),
                  Container(
                    color: Colors.white,
                    margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                    padding: EdgeInsets.fromLTRB(
                        Styles.spacing8, 0, Styles.spacing8, 0),
                    child: TextAreaWidget(
                      maxLength: 100,
                      labelText: '备注',
                      defaultValue: '',
                      placeholder: '请输入备注',
                      disabled: false,
                      required: false,
                      rows: 4,
                      onChange: (value) => this.setState(() {
                        this.setState(() {
                          remark = value;
                        });
                      }),
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                    color: Colors.white,
                    child: Column(
                      children: [
                        Padding(
                          padding: EdgeInsets.fromLTRB(
                              Styles.spacing16, Styles.spacing8, 0, 0),
                          child: Row(
                            children: <Widget>[
                              Text(
                                '照片(${this.photos.length}/6)',
                                style: TextStyle(
                                    color: Styles.DetailColor,
                                    fontSize: Styles.MiddleFont17),
                              ),
                            ],
                          ),
                        ),
                        ImageSelectWidget(
                          onchange: (value) {
                            this.setState(() {
                              this.setState(() {
                                photos = value;
                              });
                            });
                          },
                        ),
                      ],
                    ),
                  )
                ],
              ),
            ),
          ),
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
        floatingActionButton: Container(
          padding: EdgeInsets.fromLTRB(
              Styles.spacing8, Styles.spacing8, Styles.spacing8, 10),
          child: Container(
            decoration: new BoxDecoration(
              //背景
              color: Styles.BlueColor,
              //设置四周圆角 角度
              borderRadius: BorderRadius.all(Radius.circular(12.0)),
            ),
            child: FlatButton(
              disabledColor: Styles.SelectColor,
              onPressed: () {
                FocusScope.of(context).requestFocus(new FocusNode());
                if(justifyInput()){
                  showDialog(
                      barrierDismissible: false,
                      context: this.context,
                      builder: (BuildContext context) {
                        return AlertDialog(
                          title: Text('注意'),
                          content: Text('确认提交吗？'),
                          actions: <Widget>[
                            new Container(
                              child: FlatButton(
                                child: new Text(
                                  "取消",
                                  style: TextStyle(color: Colors.black),
                                ),
                                onPressed: () {
                                  Navigator.pop(context);
                                },
                              ),
                            ),
                            new Container(
                              child: FlatButton(
                                child: new Text(
                                  "确定",
                                  style: TextStyle(color: Colors.red),
                                ),
                                onPressed: () {
                                  Navigator.pop(context);

                                  this.addImage();
                                },
                              ),
                            ),
                          ],
                        );
                      });
                }

              },
              child: Container(
                height: Styles.MainButtonHeight,
                alignment: Alignment.center,
                child: Text(
                  '确定提交',
                  style: TextStyle(
                      fontSize: Styles.MainButtonTextFont, color: Colors.white),
                ),
              ),
            ),
          ),
        ));
  }
}
